package com.boot.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.boot.annotation.FieldNameMy;
import com.boot.entity.Student;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class LogUtil {
    /**
     * 保存修改日志
     * @param newObj 更新后数据
     * @param oldObj 更新前数据
     * @param businessType 业务类型
     * @param businessNo 业务主键
     * @param clazz
     * @return
     */
    public static  int saveLog(Object newObj, Object oldObj, String businessType, String businessNo, Class clazz) {

        if (newObj == null || oldObj == null) {
            return 0;
        }
        //这里对应上面日志表实体类

        //通过hutool BeanUtil工具将实体类转换为Map
        Map newMap = BeanUtil.beanToMap(newObj);
        Map oldMap = BeanUtil.beanToMap(oldObj);

        //通过类对象获取类字段
        Field[] fields = clazz.getDeclaredFields();
        Map<String, Map> changeMap = new HashMap<>();
        for (Field field : fields) {
            //判断是否有FieldName注解
            if (field.isAnnotationPresent(FieldNameMy.class)) {
                FieldNameMy fieldName = field.getAnnotation(FieldNameMy.class);
                //空的和忽略的字段不进行处理
                if (fieldName.isIgnoreNull() &&  ObjectUtil.isEmpty(newMap.get(field.getName()))) {
                    continue;
                }
                String newValue =  newMap.get(field.getName()) == null ? "" : newMap.get(field.getName()).toString();
                String oldValue =  oldMap.get(field.getName()) == null ? "" : oldMap.get(field.getName()).toString();
                String changeField;
                Map<String, String> conMap = new HashMap<>();
                //新旧记录内容不同，说明是修改过，因此记录起来
                if (!StringUtils.equals(newValue, oldValue)) {
                    //CHANGE_TEXT 自定义拼接内容
                    String CHANGE_TEXT = "fieldName-oldValue --> 调整为 --> fieldName-newValue";
                    changeField = CHANGE_TEXT.replaceAll("fieldName", fieldName.value())
                            .replaceAll("oldValue", oldValue)
                            .replaceAll("newValue", newValue);
                    conMap.put("field", field.getName());
                    conMap.put("fieldName",fieldName.value());
                    conMap.put("newValue", newValue);
                    conMap.put("oldValue", oldValue);
                    conMap.put("content", changeField);
                    changeMap.put(field.getName(), conMap);
                }
            }
        }
        System.out.println(changeMap);

        //入库（需要自己实现入库代码编写）
        return 1;
    }

    public static void main(String[] args) {
        Student student1 = new Student("1","tom","2024-05-05");
        Student student2 = new Student("2","cat","2024-05-06");

        saveLog(student1,student2,null,null,Student.class);
    }


}
